package view;

import Dto.GoodsDto;
import controller.CartController;
import controller.GoodsController;
import controller.UserController;
import model.Goods;
import model.User;
import model.common.Msg;
import utils.BeanUtil;
import utils.JSONUtil;

import java.util.List;

/**
 * @author yhl
 * @description 类说明
 * @date 2023-11-22 10:49
 * @email 2919886673@qq.com
 */
public class GoodsNormalClient extends Client {

    private final GoodsController goodsController = new GoodsController();

    private final GoodsClient goodsClient = new GoodsClient();

    private final UserController userController = new UserController();


    private final CartController cartController = new CartController();

    public String index() {
        // 输出商品列表
        goodsClient.showGoodsList();
        String result = userOperate("请选择你的操作", "B:购买商品", "A:加入购物车", "I:首页");
        if ("B".equals(result)) {
            buyGoods();
            return GN;
        } else if ("A".equals(result)) {
            addTrolley();
            return GN;
        } else if (INDEX.equals(result)) {
            return INDEX;
        }
        return INDEX;
    }

    private void addTrolley() {
        System.out.println("请输入要加入的商品编号：");
        int i = sc.nextInt();
        Goods selectGoods = getSelectGoods(i);
        String s = cartController.addCart(selectGoods);
        Msg msg = JSONUtil.JSON2Entity(s, Msg.class);
    }

    private void buyGoods() {
        System.out.println("请输入要购买的商品编号：");
        int i = sc.nextInt();
        Goods goods = getSelectGoods(i - 1);
        int num;
        while (true) {
            System.out.println("请输入要购买的数量");
            num = sc.nextInt();
            if (num > goods.getNumber()) {
                System.out.println("购买数量大于库存，请重新输入");
                continue;
            }
            break;
        }
        User loginUser = userController.getLoginUser();
        GoodsDto goodsDto = new GoodsDto();
        BeanUtil.copyProperties(goodsDto, goods);
        goodsDto.setNum(num);
        goodsDto.setState("WAITING_SEND");
        String s = goodsController.buyGoods(loginUser, goodsDto);
        Msg msg = JSONUtil.JSON2Entity(s, Msg.class);
        System.out.println(msg.getMsg());
    }

    public Goods getSelectGoods(int i) {
        String msg = goodsController.getGoodsList();
        //2.解析响应消息字符串
        Msg msgObj = JSONUtil.JSON2Entity(msg, Msg.class);
        Object obj = msgObj.getObj();   // [{}，{}]
        Object o = ((List<?>) obj).get(i);
        return JSONUtil.JSON2Entity(o.toString(), Goods.class);
    }


}
